from flask import Blueprint, render_template, request

from app.config.config import config
from app.settings import env
from common.utils import model_to_json
from model.article import Article
from model.feedback import Feedback
from model.user import User

index = Blueprint('index', __name__)


label_types = {
    'recommend': {'name': '推荐', 'selected': 'selected'},
    'auto_test': {'name': '自动化测试', 'selected': 'no-selected'},
    'python': {'name': 'Python', 'selected': 'no-selected'},
    'java': {'name': 'Java', 'selected': 'no-selected'},
    'function_test': {'name': '功能测试', 'selected': 'no-selected'},
    'perf_test': {'name': '性能测试', 'selected': 'no-selected'},
    'funny': {'name': '幽默段子', 'selected': 'no-selected'},
}


@index.route('/')
def home():
    page = request.args.get('page')
    article_type = request.args.get('article_type')

    if page is None:
        page = 1
    if article_type is None:
        article_type = 'recommend'
    article = Article()
    search_keyword = request.args.get('keyword')
    if search_keyword is not None:
        db_result = article.search_article(page, search_keyword)
    else:
        db_result = article.find_article(page, article_type)
    # print(db_result)
    for article, nickname in db_result:
        # print(article.label_name)
        article.label = label_types.get(article.label_name).get('name')
        article.create_time = str(article.create_time.month) + '.' + str(article.create_time.day)
        article.article_image = config[env].article_header_image_path + article.article_image
        article.article_tag = article.article_tag.replace(',', ' · ')

    start_num = request.args.get('start_num')
    if start_num is None:
        start_num = 0
    end_num = len(db_result)

    for k, v in label_types.items():
        if article_type == k:
            v['selected'] = 'selected'
        else:
            v['selected'] = 'no-selected'

    # user = User()
    # print(model_to_json(user.find_by_userid(3)))
    # print(model_to_json(user.find_by_userid(3)))
    # print(model_to_json(user.find_by_userid(3)))

    return render_template(
        'index.html',
        result=db_result,
        start_num=start_num,
        end_num=end_num,
        label_types=label_types
    )
